const express = require('express');
const router = express.Router();
const FocusModel = require('../../model/focus.js')
const {multerM} = require('../../model/tools.js')
const fs = require('fs');
router.get('/',async (req,res)=>{
    let result = await FocusModel.find({})
    res.render('admin/focus/index',{list:result})
})
router.get('/add',(req,res)=>{
    res.render('admin/focus/add',{})
})
router.post('/doadd', multerM().single('file'),async (req,res)=>{
    let img_focus = req.file?req.file.path.substr(6):'';
    let focus = new FocusModel(Object.assign(req.body,{img_focus,add_time:Date.now()}));
   await focus.save();
//    console.log(req.file.path)
//     res.send(req.file.path)
    res.redirect('/admin/focus')
})
router.get('/edit',async (req,res)=>{
    let id = req.query.id;
    let result =await FocusModel.find({_id:id});
    res.render('admin/focus/edit',result[0])
})
router.post('/doEdit',multerM().single('file'),async(req,res)=>{

    let id = req.body.id;

    if(req.file){
        let img_focus = req.file.path.substr(6)
        await FocusModel.updateOne({_id:id},Object.assign(req.body,{img_focus,add_time:Date.now()}))
    }else{
        await FocusModel.updateOne({_id:id},Object.assign(req.body,{add_time:Date.now()}))
    }
    res.redirect('/admin/focus')
})
router.get('/delete',async (req,res)=>{
   let id = req.query.id;
   let resultList = await FocusModel.find({_id:id});
   let delResult =  await FocusModel.deleteOne({_id:id})
   if(delResult.deletedCount==1){
    if(resultList[0].img_focus){
        fs.unlink('static/'+resultList[0].img_focus,(err)=>{
            console.log(err)
        })
    }
   }
    res.redirect('/admin/focus')
})
module.exports = router;